package com.sport.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.sport.entity.SysUser;
import com.sport.model.Result;
import com.sport.service.SysUserService;
import com.sport.utils.EmailUtils;
import com.sport.utils.PasswordUtils;
import com.sport.utils.VerificationCodeUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Tag(name = "用户注册管理")
@ApiSupport(author = "开心摆烂", order = 1)
@RequestMapping("/register")

public class RegisterController {

    @Resource
    private SysUserService userService;

    @Autowired
    private EmailUtils emailUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //发送验证码到邮箱
    @SaIgnore
    @GetMapping("/sendVerificationCode")
    @Operation(summary = "发送验证码到邮箱")
    public Result<String> sendVerificationCode(@RequestParam String email) {
        // 验证电子邮件地址格式
        try {
            InternetAddress emailAddr = new InternetAddress(email);
            emailAddr.validate();
        } catch (AddressException e) {
            return Result.error("无效的电子邮件地址格式");
        }
        String verificationCode = VerificationCodeUtils.generateVerificationCode(6);
        String subject = "个人平台注册验证码";
        String text = "欢迎来到个人平台,您的验证码是：" + verificationCode + "，请在5分钟内使用。";
        emailUtils.sendSimpleMail(email, subject, text);

        // 将验证码保存到Redis，设置过期时间为5分钟
        redisTemplate.opsForValue().set("verificationCode:" + email, verificationCode, 5, TimeUnit.MINUTES);

        return Result.success("验证码已发送","success");
    }

    //QQ发送验证码注册
    @GetMapping("/qqregister")
    @SaIgnore
    @Operation(summary = "QQ发送验证码注册")
    public Result<String> register(@RequestParam String email, @RequestParam String password, @RequestParam String verificationCode) {
        // 从Redis中获取验证码
        String storedVerificationCode = redisTemplate.opsForValue().get("verificationCode:" + email);
        if (storedVerificationCode == null) {
            return Result.error("验证码已过期，请重新获取");
        }
        if (!verificationCode.equals(storedVerificationCode)) {
            return Result.error("验证码错误");
        }

        // 验证通过，删除Redis中的验证码
        redisTemplate.delete("verificationCode:" + email);

        // 检查用户是否已存在
        SysUser existingUser = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getEmail, email));
        if (existingUser != null) {
            return Result.error("该邮箱已注册");
        }

        // 生成盐值
        String salt = RandomUtil.randomString(16);
        // 对密码进行加密
        String encryptedPassword = PasswordUtils.encrypt(salt, password);
        // 生成随机用户名
        String randomUsername = "user_" +RandomUtil.randomString(8); // 生成8位随机字符串作为用户名

        // 设置默认头像
        String defaultAvatar = "https://tdesign.gtimg.com/site/avatar.jpg";

        // 创建新用户并保存到数据库
        SysUser newUser = new SysUser();
        newUser.setEmail(email);
        newUser.setPassword(encryptedPassword);
        newUser.setSlat(salt);
        newUser.setUsername(randomUsername); // 设置随机生成的用户名
        newUser.setAvatar(defaultAvatar); // 设置默认头像
        userService.save(newUser);

        return Result.success("验证通过，注册成功","success");
    }


    @SaIgnore
    @PostMapping("/simulateUserScan")
    @Operation(summary = "用户微信扫描二维码登录")
    @Transactional
    public Result<Map<String, String>> simulateUserScan(@RequestParam String uuid, @RequestParam String openid) {
        try {

            // 检查用户是否已注册
            SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getOpenid, openid));
            if (user == null) {
                // 用户未注册，自动注册用户
                user = new SysUser();
                user.setOpenid(openid);
                user.setUsername("user_" + RandomUtil.randomString(8)); // 生成随机用户名
                String slat = RandomUtil.randomString(16); // 生成盐值
                user.setSlat(slat);
                user.setPassword(PasswordUtils.encrypt(slat, "123456")); // 设置默认密码为123456
                user.setAvatar("https://tdesign.gtimg.com/site/avatar.jpg"); // 设置默认头像
                userService.save(user);
                // 添加日志验证盐值和密码
                System.out.println("Generated Salt: " + slat);
                System.out.println("Generated Encrypted Password: " + user.getPassword());
            }
            // 更新二维码状态和用户ID
            redisTemplate.opsForValue().set("qrCode:" + uuid, "success");
            redisTemplate.opsForValue().set("qrCodeUserId:" + uuid, String.valueOf(user.getId()), 5, TimeUnit.MINUTES);
            // 生成 Token
            StpUtil.login(user.getId(), "wx");
            Map<String, String> map = new HashMap<>();
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            map.put("tokenHead", tokenInfo.tokenName);
            map.put("token", tokenInfo.tokenValue);
            return Result.success("登录成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("用户扫描处理失败");
        }
    }


}
